#include <iostream>
#include <stdio.h>
#include <math.h>

#include <SDL/SDL.h>
#include <GL/gl.h>

#include "Object3D.h"
#include "Vertex3D.h"
#include "Triangle.h"
#include "Mesh.h"

#define MAXLINE 300

using namespace std;

Object3D *
read_orj (const char *path) 
{
  int line = 0;
  char staux[MAXLINE];
  float a, b, c;
  GLdouble aux[3];
  float vx, vy, vz;
  FILE *f;
 
	vector<Vertex3D *> vertices;
	vector<Triangle *> triangs;	
 
  if(!(f = fopen (path, "r")))
    {
      cerr << "File: " << path << " not found!" << endl;
      exit(-1);
    }
  
  while (fgets(staux, MAXLINE, f)!=NULL){

    line++;

    switch(staux[0]){

      // Comment.
    case '#': break;

      // Vertex.
    case 'v': 

      // Read the x, y and z values.
      sscanf(&staux[2], "%f %f %f", &vx, &vy, &vz);

      aux[0] = vx; aux[1] = vy; aux[2] = vz;
      // Append a new vertex.
      vertices.push_back(new Vertex3D(aux));

      break;

      // Face.
    case 'f': 

      sscanf(&staux[2], "%f %f %f", &a, &b, &c);
			
			Vertex3D  *t[3] = {vertices[--a], vertices[--b], vertices[--c]};
      // Store the vertex pointers.
      triangs.push_back (new Triangle(t));

      break;

    }// End switch.

  }// End while.
  
	fclose (f);
	
	Object3D *o = new Object3D ();
	for (vector<Vertex3D *>::iterator it = vertices.begin (); it != vertices.end (); it++)
		o->add_vertex (*it);
	for (vector<Triangle *>::iterator it = triangs.begin (); it != triangs.end (); it++)
		o->add_triangle (*it);

	o->compute_com ();
	return o;

}
